問題描述
如何將 Wagtail 'admin' 菜單添加到自定義模板? (How to add Wagtail 'admin' menu to custom templates?)
在源自 Wagtail 頁面模型的模板上,右下角有一個小 Wagtail 圖標/菜單。這提供了一種快速編輯頁面和/或跳轉到 Wagtail 管理員的方法。但是,此菜單不會出現在不是從 Wagtail 頁面模型派生的自定義視圖模板上。
我如何告訴 Wagtail 在我的前端模板上顯示小菜單,以便頁面具有一致的導航?
參考解法
方法 1:
The standard Wagtail user bar is rendered by placing in your template:
{% load wagtailuserbar %}
{% wagtailuserbar 'top‑left' %}
I typically just put the above in base.html
. The 'top‑left'
designation, of course, tells the template tag where to render the user bar. Reference
However, the wagtailuserbar is only rendered for Wagtail pages. What you want to do is render the user bar with only the Go to Wagtail Admin option (because no other options would be relevant). Therefore, you could create your own template tag and place it in base.html
beside the wagtailuserbar
. You would set it up so that it renders if there IS NO page
in the context (the wagtailuserbar
template tag checks to make sure there IS a page
in the context). To create your tag, just start with the code from wagtailuserbar.py
and modify it to create a template tag called wagtailuserbar_admin_only
(untested):
from django import template
from django.template.loader import render_to_string
from wagtail.admin.templatetags.wagtailuserbar import get_page_instance
from wagtail.admin.userbar import (AdminItem)
@register.simple_tag(takes_context=True)
def wagtailuserbar_admin_only(context, position='bottom‑right'):
# Find request object
try:
request = context['request']
except KeyError:
return ''
# Don't render without a user because we can't check their permissions
try:
user = request.user
except AttributeError:
return ''
# Don't render if user doesn't have permission to access the admin area
if not user.has_perm('wagtailadmin.access_admin'):
return ''
# Only render if the context does NOT contain a variable referencing a saved page
page = get_page_instance(context)
if page:
return ''
# Render the items
rendered_items = [AdminItem()]
# Render the userbar items
return render_to_string('wagtailadmin/userbar/base.html', {
'request': request,
'items': rendered_items,
'position': position,
})
Then, to use in templates, place in base.html
:
{% load wagtailuserbar_admin_only %}
{% wagtailuserbar_admin_only 'top‑left' %}
(by Brylie Christopher Oxley、Dan Swain)